package com.ztjava.weixin.controller;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.jfinal.aop.Duang;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.member.ApiClient;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.core.utiliy.RequestUtil;
import com.ztjava.plugin.event.EventKit;
import com.ztjava.plugin.event.core.RequestEvent;
import com.ztjava.plugin.weixin.WeixinKit;
import com.ztjava.plugin.weixin.WeixinSdk;
import com.ztjava.weixin.model.message.MessageReply;
import com.ztjava.weixin.model.scene.SceneForever;
import com.ztjava.weixin.model.scene.SceneLimit;
import com.ztjava.weixin.service.SceneService;

@ControllerClass(client=ApiClient.class,path="/weixin")
public class WeixinApiController extends BaseController{
	private static SceneService sceneService = Duang.duang(SceneService.class);
	
	public void index(){
		WeixinSdk weixinSdk = WeixinKit.use();
		if(!weixinSdk.checkSignature(getPara("signature",""),getPara("timestamp",""),getPara("nonce",""))){
			renderError(404);
			return;
		}
		if(getRequest().getMethod().equalsIgnoreCase("Get")){
			renderText(getPara("echostr",""));
			return;
		}
		Element root = null;
		try{
			Document document = DocumentHelper.parseText(RequestUtil.readData(getRequest()));
			root = document.getRootElement();
		}catch (Exception e) {
			e.printStackTrace();
			renderNull();
			return;
		}
		
		String msgType = root.element("MsgType").getText().toLowerCase();
		Cache cache = Redis.use();
		switch (msgType) {
			//受理文本消息
			case "text":
				String content = root.element("Content").getText();
				if(cache.hexists(Constant.R_PRE+"WEIXIN:MESSAGE:RULE", "text_"+content)){
					MessageReply messageReply = cache.hget(Constant.R_PRE+"WEIXIN:MESSAGE:RULE", "text_"+content);
					weixinSdk.custom_send(root.element("FromUserName").getText(), messageReply.getStr("type"), messageReply.getStr("content"));
				}else if(ViewTool.param("WEIXIN_KEFU","F").equals("T")) {
					renderText(WeixinKit.transfer_customer_service(root.element("FromUserName").getText(),
							root.element("ToUserName").getText()));
					return;
				}
				break;
			//受理事件消息
			case "event":
				String event = root.element("Event").getText();
				//关注事件
				if((event.equals("subscribe")||event.equals("SCAN"))&&root.element("EventKey")!=null&&!root.element("EventKey").getText().equals("")){
					if(root.element("EventKey")!=null&&!root.element("EventKey").getText().equals("")){
						String eventKey = root.element("EventKey").getText();
						Integer scene_id =  Integer.parseInt(eventKey.replace("qrscene_", ""));
						if(scene_id<=100000){
							SceneForever sceneForever = SceneForever.dao.findById(scene_id);
							sceneForever.put("openid", root.element("FromUserName").getText());
							//其它模块定义的参数二维码
							if(sceneForever.get("event")!=null&&!sceneForever.getStr("event").equals("")){
								EventKit.postRemoteOnly(sceneForever.getStr("event"), new RequestEvent(sceneForever.toRecord()));
							}
							if(event.equals("subscribe")&&sceneForever.getStr("is_record").equals("T")){
								sceneService.insertRecord(scene_id, root.element("FromUserName").getText());
							}
						}else {
							SceneLimit sceneLimit = SceneLimit.dao.findById(scene_id-100000);
							sceneLimit.put("openid", root.element("FromUserName").getText());
							EventKit.postRemoteOnly(sceneLimit.getStr("event"), new RequestEvent(sceneLimit.toRecord()));
						}
					}
				}
				String ruleKey = "event_"+event+"_";
				if(root.element("EventKey")!=null&&!root.element("EventKey").getText().equals("")){
					String eventKey = root.element("EventKey").getText();
					if(event.equals("subscribe")) eventKey = eventKey.replace("qrscene_", "");
					ruleKey = ruleKey + eventKey;
				}
				if(cache.hexists(Constant.R_PRE+"WEIXIN:MESSAGE:RULE",ruleKey)){
					MessageReply messageReply = cache.hget(Constant.R_PRE+"WEIXIN:MESSAGE:RULE",ruleKey);
					weixinSdk.custom_send(root.element("FromUserName").getText(), messageReply.getStr("type"), messageReply.getStr("content"));
				}
				break;
			default:
				if(ViewTool.param("WEIXIN_KEFU","F").equals("T")) {
					renderText(WeixinKit.transfer_customer_service(root.element("FromUserName").getText(),
							root.element("ToUserName").getText()));
					return;
				}
				break;
		}
		renderNull();
		return;
	}
}
